using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace WebApplicationTokenDemo.Controllers
{
    
     
    [ApiController]
    public class TestController:ControllerBase
    {

        [Authorize]
        [Route("getname")]
        [HttpGet]
        public async Task<String> GetClaims()
        {

            var user = HttpContext.User;
            Console.WriteLine(user.Identity.IsAuthenticated);
            return "123";
        }

        [Route("gettoken")]
        [HttpGet]
        public IActionResult GetToken()
        {
             

            //JWT载荷(Payload)
            var key = Encoding.ASCII.GetBytes("1234567890123456");
            var authTime = DateTime.UtcNow;
            var expiresAt = authTime.AddDays(7);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                //内容
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(JwtClaimTypes.Audience,"api"),
                   // new Claim(JwtClaimTypes.Issuer,"http://localhost:5001"),
                    new Claim(JwtClaimTypes.Id, "1234"),
                    new Claim(JwtClaimTypes.Name, "test"),
                    
                    
                }),
                 
                //过期时间
                Expires = expiresAt,
                //签证
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            return Ok(new
            {
                access_token = tokenString,
                token_type = "Bearer" 
               
            });
        }
    }
}